package net.wanho.shiro.filter;

import net.wanho.shiro.token.JwtToken;
import net.wanho.util.JwtUtils;
import net.wanho.util.ServletUtils;
import net.wanho.vo.AjaxResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * Author：汤小洋
 * Date：2023-07-27 16:41
 * Description：<描述>
 */
public class JwtFilter extends AccessControlFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        HttpServletRequest request = WebUtils.toHttp(servletRequest);

        /**
         * 如果前端发送跨域请求且自定义了请求头，那么会先发送一个OPTIONS请求，这个请求是不带token的，用于获取服务器的相关信息，称为预检请求
         * 这是浏览器本身的机制，我们需要忽略这个请求，否则会导致跨域请求失败
         */
        if("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }

        // 获取请求头中的token
        String authorization = request.getHeader("Authorization");
        if(StringUtils.isEmpty(authorization)){
            ServletUtils.writeJson(AjaxResult.error(HttpStatus.UNAUTHORIZED.value(), "请先登录"));
            return false;
        }
        authorization = authorization.replace("Bearer ", "");

        // 调用Shiro认证
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new JwtToken(authorization));
        } catch (AuthenticationException e) {
            e.printStackTrace();
            ServletUtils.writeJson(AjaxResult.error("token无效"));
            return false;
        }
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        return false;
    }
}
